package aimis.controller;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import aimis.constant.ResponseEnum;
import aimis.domain.Role;
import aimis.dto.PageQuery;
import aimis.dto.Result;
import aimis.dto.TableList;
import aimis.dto.form.RoleForm;
import aimis.repo.AuthorityRepo;
import aimis.repo.RoleRepo;

import java.util.List;

@RestController
public class RoleController {
    @Autowired
    private RoleRepo roleRepo;
    @Autowired
    private AuthorityRepo authorityRepo;

    @PostMapping("/role/add")
    public Result add(@RequestBody @Validated(RoleForm.AddRole.class) RoleForm roleForm) {
        //Form对象-》Domain对象
        Role role = new Role();
//        role.setSort(roleForm.getSort());
//        role.setName(roleForm.getName());
        BeanUtils.copyProperties(roleForm, role);
        for (var id : roleForm.getAuthorityIds()) {
            var authority = authorityRepo.findById(id);
            role.getAuthorities().add(authority.get());

        }
        roleRepo.save(role);
        return Result.success(ResponseEnum.OK);
    }

    @PostMapping("/role/edit")
    public Result edit(@RequestBody @Validated(RoleForm.EditRole.class) RoleForm roleForm) {
        //Form对象-》Domain对象
        var findOne = roleRepo.findById(roleForm.getId());
        var role = findOne.get();
        BeanUtils.copyProperties(roleForm, role);
        role.getAuthorities().clear(); //清空角色权限
        for (var id : roleForm.getAuthorityIds()) {
            var authority = authorityRepo.findById(id);
            role.getAuthorities().add(authority.get());
        }
        roleRepo.save(role);
        return Result.success(ResponseEnum.OK);
    }

    @PostMapping("/role/get")
    public Result get(Long id) {
        var role = roleRepo.findById(id);
        if (role.isPresent()) {
            return Result.success().add("role", role);
        } else {
            return Result.error(ResponseEnum.DATA_NOT_EXIST);
        }
    }

    @PostMapping("/role/delete")
    public Result delete(@RequestBody @Validated(RoleForm.DeleteRole.class) RoleForm roleForm) {
        //Form对象-》Domain对象
        roleRepo.deleteById(roleForm.getId());
        return Result.success(ResponseEnum.OK);
    }

    @PostMapping(value = "/role/findByQuery")
    public TableList<Role> findByQuery(String name, PageQuery pageQuery) {
        var pageable = pageQuery.toPageable();
        if (name != null && name.isBlank())
            name = null;
        var roles = roleRepo.findByQuery(name, pageable);
        return TableList.create(roles);
    }

    @PostMapping(value = "/role/findAll")
    public List<Role> findAll() {
        return roleRepo.findAll();
    }
}
